#include "dht11.h"


void delay(uint16_t us)
{
	//clear current value
	__HAL_TIM_SET_COUNTER(&htim3, 0);
	while(__HAL_TIM_GET_COUNTER(&htim3) < us) 
	{}
}

void dht11_pin_in()
{
	GPIO_InitTypeDef GPIO_InitStruct = {0};
	
	GPIO_InitStruct.Pin = DHT11_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
  HAL_GPIO_Init(DHT11_GPIO_Port, &GPIO_InitStruct);
}
	
void dht11_pin_out()
{
	GPIO_InitTypeDef GPIO_InitStruct = {0};
	
	GPIO_InitStruct.Pin = DHT11_Pin;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
  HAL_GPIO_Init(DHT11_GPIO_Port, &GPIO_InitStruct);
}


void dht11_read(float* temp, float* humid)
{
	uint8_t data[5] = {0,0,0,0,0};
	
	DHT11_PIN_LOW;
	HAL_Delay(18);
	DHT11_PIN_HIGH;
	delay(40);
	dht11_pin_in();
	
	delay(20);
	while(DHT11_PIN_READ == GPIO_PIN_RESET) 
	{}
	
	while(DHT11_PIN_READ == GPIO_PIN_SET) 
	{}
		
	for(uint8_t i=0 ; i<5; ++i ) {
		
		for(uint8_t k=0 ; k<8; ++k ) {
			
			while(DHT11_PIN_READ == GPIO_PIN_RESET) 
			{}
				
			__HAL_TIM_SET_COUNTER(&htim3, 0);	
			while(DHT11_PIN_READ == GPIO_PIN_SET) 
			{}
			uint16_t value = __HAL_TIM_GET_COUNTER(&htim3);
				
				data[i] <<= 1;
				
				if(value > 45) {
					data[i] |= 0x01;
				}
		}
	}
	float factor = 0.00392f; //  1/255
	*temp = data[2] + (data[3] * factor);
	*humid = data[0] * + (data[1] * factor);
}
	